<template>
  <div>
    <top-nav-bar :applyPageRoute="nowRouteTitle" @back="$router.go(-1)"></top-nav-bar>
    <a-card :bordered="false" :bodyStyle="{ padding: '16px', height: '100%' }">
      <a-alert type="success" style="border: none; border-radius: 5px; background: #fff0e7; padding: 4px 12px">
        <div slot="description">
          <div>注意事项:</div>
          <div class="tip-font">1.仅支持对按课时收费的课程修正剩余课时，修正课时不会给家长发送微信提醒。</div>
          <div class="tip-font">2.剩余课时=购买课时+赠送课时-导入课时-点名课时-退转课时。</div>
          <div class="tip-font">3.由于导入课时需大于等于0，所以“剩余课时≤购买课时+赠送课时-点名课时-退转课时”。</div>
          <div class="tip-font">4.修正剩余课时会更改导入课时数值，其他数值不会被更改。</div>
        </div>
      </a-alert>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="搜索学员:">
                <a-input
                  v-model="keywords"
                  placeholder="请输入学员姓名/手机号(回车搜索)"
                  @pressEnter="$refs.table.refresh(true)"
                  style="width: 80%"
                >
                  <a-tooltip slot="suffix" title="请输入学员姓名/手机号">
                    <a-icon type="search" style="color: rgba(0, 0, 0, 0.45)" @click="$refs.table.refresh(true)" />
                  </a-tooltip>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="搜索订单号:">
                <a-input
                  v-model="orderNo"
                  placeholder="请输入订单号(回车搜索)"
                  @pressEnter="$refs.table.refresh(true)"
                  style="width: 80%"
                >
                  <a-tooltip slot="suffix" title="请输入订单号">
                    <a-icon type="search" style="color: rgba(0, 0, 0, 0.45)" @click="$refs.table.refresh(true)" />
                  </a-tooltip>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="报读课程:">
                <a-select v-model="queryParam.course_id" placeholder="请选择课程" allowClear style="width: 80%">
                  <a-select-option v-for="(item, index) in courseList" :key="index" :value="item.id">{{
                    item.name
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="经办日期:">
                  <a-range-picker @change="expireChange" />
                </a-form-item>
              </a-col>
            </template>
          </a-row>
        </a-form>
        <a style="cursor: pointer" v-if="advanced" @click="advanced = !advanced" id="moreButton">
          收起
          <a-icon type="up"></a-icon>
        </a>
        <a style="cursor: pointer" v-if="!advanced" @click="advanced = !advanced" id="moreButton">
          展开
          <a-icon type="down"></a-icon>
        </a>
      </div>
      <div style="margin: 10px 0">
        <a-button @click="clickEdit" v-if="selectedRowKeys.length == 0">批量修改</a-button>
        <div v-else style="display: flex">
          <div class="selected-data-box">
            <a-icon type="exclamation-circle" theme="filled" style="color: #ff8534" />
            <span style="margin-left: 10px; margin-right: 20px">已选择{{ selectedRowKeys.length }}项</span>
            <a @click="clear">清空</a>
          </div>
          <a-button @click="correctEdit">批量修改</a-button>
          <!--  -->
        </div>
      </div>
      <s-table
        ref="table"
        rowKey="key"
        :columns="columns"
        :data="loadData"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        showPagination="auto"
        class="user_management_table"
        :scroll="{ x: 1300 }"
      >
        <!-- 经办日期 -->
        <span slot="purchase_at" slot-scope="text, record">
          {{ record.order.purchase_at | dayjs }}
        </span>
        <!-- 修正剩余课时 -->
        <span slot="correct_surplus_number" slot-scope="text,record,index">
          <a-input-number v-model="record.correct_number"  :min="0" :max="record.correct_number_max"  @change="correctHour(record,index)"/>
          <a-icon
            type="arrow-up"
            style="margin-left: 8px; color: #5dd333"
            v-if="record.correct_number > record.surplus_number"
          />
          <a-icon
            type="arrow-down"
            style="margin-left: 8px; color: #5dd333"
            v-if="record.correct_number < record.surplus_number"
          />
        </span>
      </s-table>
    </a-card>
    <div style="padding-top: 60px"></div>
    <div class="foot-box">
      <a-button type="primary" class="ml12" @click="finsh">确定</a-button>
      <a-button @click="$router.go(-1)">取消</a-button>
    </div>
    <!-- 批量修改课时 -->
    <a-modal
      title="批量修改课时"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="visible = false"
    >
      <div style="margin-bottom: 20px">
        共选择{{ selectedRowKeys.length }}条数据，支持批量修改为≤{{ correctMaxNum }}的值
      </div>
      <div>
        <span style="font-size: 16px; font-weight: 500; margin-right: 12px">剩余课时</span>
        批量修改为： <a-input-number :min="0" :max="correctMaxNum" v-model="updateClassHour"/>
      </div>
    </a-modal>
  </div>
</template>

<script>
import topNavBar from '@/components/topNavBar/topNavBar'
import { coursesList } from '@/api/courseCharge'
import { STable, Ellipsis } from '@/components'
import { surplusHour, correctClassHour } from '@/api/student'
export default {
  components: {
    topNavBar,
    STable,
    Ellipsis,
  },
  data() {
    return {
      visible: false,
      confirmLoading: false,
      correctMaxNum: 1,
      updateClassHour: 0,
      nowRouteTitle: '',
      courseList: [],
      //搜索
      keywords: '',
      orderNo: '',
      queryParam: {
        school_id: this.$store.state.user.school,
      },
      advanced: false, //展开
      //表格
      selectedRowKeys: [],
      selectedRows: [],
      rowSelection: {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      },
      tableDate: [],
      columns: [
        {
          title: '学员姓名',
          dataIndex: 'orderStudent.name',
          width: 200,
          fixed: 'left',
          // scopedSlots: { customRender: 'student_name' },
        },
        {
          title: '报读课程',
          dataIndex: 'project.name',
          width: 200,
          fixed: 'left',
          // scopedSlots: { customRender: 'student_name' },
        },
        {
          title: '订单号',
          dataIndex: 'order.order_no',
          width: 300,
          // scopedSlots: { customRender: 'student_name' },
        },
        {
          title: '经办日期',
          // dataIndex: 'student_name',
          width: 200,
          scopedSlots: { customRender: 'purchase_at' },
        },
        {
          title: '购买课时',
          dataIndex: 'buy_number',
          width: 200,
          // scopedSlots: { customRender: 'student_name' },
        },
        {
          title: '赠送课时',
          dataIndex: 'give_number',
          width: 200,
          // scopedSlots: { customRender: 'student_name' },
        },
        {
          title: '退转课时',
          dataIndex: 'refund_number',
          width: 200,
          // scopedSlots: { customRender: 'student_name' },
        },
        {
          title: '已消耗导入课时',
          dataIndex: 'import_number',
          width: 200,
          // scopedSlots: { customRender: 'student_name' },
        },
        {
          title: '已消耗点名课时',
          dataIndex: 'call_number',
          width: 150,
          // scopedSlots: { customRender: 'student_name' },
        },
        {
          title: '当前剩余课时',
          dataIndex: 'surplus_number',
          width: 150,
          align: 'right',
          // scopedSlots: { customRender: 'student_name' },
          fixed: 'right',
        },
        {
          title: '修正剩余课时',
          // dataIndex: 'student_name',
          width: 150,
          scopedSlots: { customRender: 'correct_surplus_number' },
          fixed: 'right',
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        return surplusHour(
          Object.assign(parameter, this.queryParam, { keywords: this.keywords, order_no: this.orderNo })
        ).then((res) => {
          this.selectedRowKeys = []
          this.selectedRows = []
          if (res.data.length > 0) {
            res.data.forEach((item) => {
              item.correct_number_max = item.buy_number + item.give_number-item.call_number
              item.correct_number = item.surplus_number
            })
            this.tableDate = res.data
          }
          return res
        })
      },
      params: [], //修正剩余课时改变后提交的数据
    }
  },
  watch: {
    queryParam: {
      handler(newName, oldName) {
        this.$refs.table.refresh(true)
        this.sumNumber()
      },
      //immediate:true代表如果在 wacth 里声明了obj之后，就会立即先去执行里面的handler方法，
      immediate: false,
      deep: true, // 开启深度监听，默认是false
    },
  },
  created() {
    this.nowRouteTitle = this.$route.meta.title
    this.getCourseList()
  },
  methods: {
    getCourseList() {
      coursesList({ school_id: this.queryParam.school_id, pageSize: 999999 })
        .then((res) => {
          this.courseList = res.data
        })
        .catch((error) => {
          this.$message.error(err.data.message || '获取课程列表失败，请稍后重试')
        })
    },
    expireChange(date, dateString) {
      this.queryParam.purchase_start_at = dateString[0]
      this.queryParam.purchase_end_at = dateString[1]
      this.$refs.table.refresh(true)
    },
    //表格
    onSelectChange(selectedRowKeys, selectedRows) {
      console.log(selectedRowKeys, selectedRows)
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    classHourCorrect(e, data) {
      console.log(e, data)
      data.correct_number = e
      // if (data.correct_number != '') {
      // this.params.push({
      //   order_content_id: data.id,
      //   hour: data.correct_number,
      // })
      // }
      // } else {
      //   this.params.forEach((item) => {
      //     if (item.order_content_id == data.id) {
      //       item.hour = data.correct_number
      //     }
      //   })
      //   for (let i = 0; i < this.params.length; i++) {
      //     if (this.params[i].order_content_id != data.id) {
      //       this.params.push({
      //         order_content_id: data.id,
      //         hour: data.correct_number,
      //       })
      //       return
      //     }
      //   }
      // }
    },
    correctHour(data,index){
     
      // if(data.correct_number==''){
      //    data.correct_number=data.correct_number_max
      //    console.log(data.correct_number);
      //    this.$forceUpdate()
      // }
      data.import_number=data.correct_number_max-data.correct_number
      
    },
    clickEdit() {
      if (this.selectedRowKeys.length == 0) {
        this.$message.warning('请选择要修改课时的学员')
        return
      }
    },
    clear() {
      this.selectedRowKeys = []
      this.selectedRows = []
    },
    correctEdit() {
      if (this.selectedRows.length > 1) {
        let minIndex = 0
        this.correctMaxNum = this.selectedRows[0].buy_number + this.selectedRows[0].give_number
        for (let i = 0; i < this.selectedRows.length; i++) {
          if (Number(this.selectedRows[i].buy_number) + Number(this.selectedRows[i].give_number) < this.correctMaxNum) {
            this.correctMaxNum = Number(this.selectedRows[i].buy_number) + Number(this.selectedRows[i].give_number)
          }
        }
      } else {
        this.correctMaxNum = this.selectedRows[0].buy_number + this.selectedRows[0].give_number
        this.updateClassHour = this.correctMaxNum
      }
      this.visible = true
    },
    handleOk() {
      this.confirmLoading = true
      console.log(this.selectedRows)

      this.selectedRows.forEach((item) => {
        item.correct_number = this.updateClassHour
      })
      this.confirmLoading = false
      this.visible = false
      // this.selectedRows.forEach((item) => {
      //   params.push({
      //     order_content_id: item.id,
      //     hour: this.updateClassHour,
      //   })
      // })
      // correctClassHour({data:params})
      //   .then((res) => {
      //     this.selectedRowKeys = []
      //     this.selectedRows = []
      //     this.$message.success('课时修改成功')
      //     this.$refs.table.refresh(true)
      //     this.confirmLoading = false
      //     this.visible = false
      //   })
      //   .catch((err) => {
      //     this.$message.error(err.data.message || '课时修改失败')
      //     this.confirmLoading = false
      //   })
    },
    finsh() {
      let params = []
      this.tableDate.forEach((item) => {
        if (item.correct_number != item.surplus_number) {
          params.push({
            order_content_id: item.id,
            hour: item.correct_number,
          })
        }
      })
      if (params.length == 0) {
        this.$message.success('课时修改成功')
        this.$router.go(-1)
      } else {
        correctClassHour({ data: params })
          .then((res) => {
            this.$message.success('课时修改成功')
            this.$router.go(-1)
          })
          .catch((err) => {
            this.$message.error(err.data.message || '课时修改失败')
          })
      }
    },
  },
}
</script>

<style lang="less" scoped>
.tip-font {
  margin-left: 20px;
  font-size: 12px;
  line-height: 26px;
}
.table-page-search-wrapper {
  margin-top: 30px;
  position: relative;
}
#moreButton {
  position: absolute;
  right: 0;
  top: 5px;
}
.selected-data-box {
  min-width: 160px;
  background: #fff0e7;
  padding: 0 12px;
  border-radius: 4px;
  height: 32px;
  line-height: 32px;
  margin-right: 10px;
}
.foot-box {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 48px;
  line-height: 48px;
  background: #fff;
  padding: 10px 48px;
  display: flex;
  flex-direction: row-reverse;
}
.ml12 {
  margin-left: 12px;
}
</style>